package cn.client.ui.view.main.dynamic

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import cn.client.R
import cn.client.data.remoteData.bean.DateUtils
import cn.client.data.remoteData.bean.DynamicData
import cn.client.data.remoteData.bean.TakeD
import coil.compose.AsyncImage
import kotlinx.coroutines.launch

/**
 * 动态信息
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DynamicInfo(
    dynamicId: Int,
    authorId: Int,
    viewModel: DynamicViewModel = hiltViewModel()
){
    val context = LocalContext.current
    val getDynamicById: TakeD = TakeD(id = dynamicId, uid = authorId)
    // 观察动态信息的状态
    val dynamicDataResState = viewModel.dynamicDataRes.collectAsState(initial = null)
    val dynamicDataRes = dynamicDataResState.value

    // 如果为空就发送请求
    if (dynamicDataRes == null){
        viewModel.dispatch(DynamicViewModel.PageIntent.GetDynamic(getDynamicById))
    }

    val coroutineScope = rememberCoroutineScope()
    var createDate: String = ""

    coroutineScope.launch {
        dynamicDataRes?.gmtCreate.let { it->
            createDate = it?.let { it1 -> DateUtils.dateToStr(it1) }.toString()
        }
    }

    LaunchedEffect(Unit){
        viewModel.pageEvents.collect{
            if (it is DynamicViewModel.PageEvent.Error){
                Toast.makeText(context,"错误：${it.error}", Toast.LENGTH_LONG).show()
            }
        }
    }
    /* 动态内容视图 */
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        /* 顶部导航栏 */
        TopAppBar(
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.primary
            ),
            title = { Text("动态信息") },
            /* 左边按钮 */
            navigationIcon = { IconButton( onClick = {
                /* 点击事件：返回 */

            } ) { Icon(Icons.AutoMirrored.Filled.ArrowBack, null) } },
        )
        Spacer(modifier = Modifier
            .height(5.dp)
            .fillMaxWidth())
        /* 用户卡片 */
        Row(modifier = Modifier
            .padding(all = 5.dp)
            .fillMaxWidth(),
            horizontalArrangement = Arrangement.Start,//设置水平居左对齐
            verticalAlignment =  Alignment.CenterVertically//设置垂直居中对齐
        ) {
            DynamicAuthorItem(dynamicCreateDate = createDate)
        }

        dynamicDataRes?.let {
            /* 动态内容视图 */
            Surface(
                modifier = Modifier
                    .padding(5.dp)
                    .fillMaxWidth()
                    .wrapContentHeight()
            ){
                DynamicInfoContent(
                    dynamicData = it
                )
            }
            /* 用户行为控件 */
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.End,//设置水平居右对齐
            ) {
                UserAction( )
            }
        }
    }
}


/**
 * 动态作者Item
 */
@Composable
fun DynamicAuthorItem(
    dynamicCreateDate: String
){
        /* 用户头像 和 用户名 */
        Row(
            modifier = Modifier.wrapContentWidth(),
            horizontalArrangement = Arrangement.Center,//设置水平居中对齐
            verticalAlignment =  Alignment.CenterVertically//设置垂直居中对齐
        ) {
            Image(
                painter = painterResource(R.drawable.ab1_inversions),
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .size(50.dp)
                    .clip(CircleShape)
                    .border(1.dp, MaterialTheme.colorScheme.primary, CircleShape)
            )
            Spacer(modifier = Modifier
                .width(5.dp)
                .wrapContentHeight())
            Column {
                Text(
                    text = "username",
                    color = MaterialTheme.colorScheme.secondary,
                    style = MaterialTheme.typography.titleSmall)
                Spacer(modifier = Modifier
                    .height(5.dp)
                    .wrapContentWidth())
                Row(
                    verticalAlignment =  Alignment.CenterVertically//设置垂直居中对齐
                ) {
                    Text(
                        text = "发布于 $dynamicCreateDate ",
                        color = MaterialTheme.colorScheme.secondary,
                        style = MaterialTheme.typography.titleSmall)
                }
            }
        }
    }

/**
 * 动态内容
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun DynamicInfoContent(
    dynamicData: DynamicData
){
    var isExpanded by remember { mutableStateOf(false) }
    // pageCount（分页器页数）由图片数量决定
    val pagerState = rememberPagerState(initialPage = 1, pageCount = { dynamicData.images?.size ?:0 })

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
    ) {
        Spacer(modifier = Modifier.height(10.dp).fillMaxWidth())
        /* 文本内容 */
        Row(
            modifier = Modifier
                .padding(5.dp)
                .clickable { isExpanded = !isExpanded }
        ) {
            Text(text = dynamicData.content,  maxLines = if (isExpanded) Int.MAX_VALUE else 2 )
        }
        if (dynamicData.images.isNullOrEmpty()) {
            Log.d("DynamicInfoContent","没有图片：${dynamicData.images?.size}")
            // 如果没有图片，显示占位符
            Spacer(modifier = Modifier
                .fillMaxWidth()
                .height(5.dp))
        } else {
            // 使用HorizontalPager来实现轮播图
            HorizontalPager(
                beyondBoundsPageCount = 2,
                state = pagerState,
                modifier = Modifier
                    .fillMaxWidth()
                    .fillMaxHeight()
            ) { page ->
                // 获取当前页面的图片数据
                val image = dynamicData.images[page]
                /* 轮播图 */
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .fillMaxHeight(0.5f)
                        .background(Color.DarkGray),
                    horizontalArrangement = Arrangement.Center
                ) {
                    AsyncImage(
                        model = image.image,
                        contentDescription = null,
                        modifier = Modifier
                            .fillMaxHeight(),
                        contentScale = ContentScale.Crop
                    ) }
                }
            }
        }
    }





/**
 * 用户行为控件：点赞、评论
 */
@Composable
fun UserAction(

){
    var isLike by remember { mutableStateOf(false) }
    var likedNum by remember { mutableStateOf(0) }

    var isComment by remember { mutableStateOf(false) }
    val commentNum by  remember { mutableStateOf(0) }

    Row (
        horizontalArrangement = Arrangement.Center,//设置水平居中对齐
        verticalAlignment =  Alignment.CenterVertically//设置垂直居中对齐
    ){
        /* 点赞数量 */
        Text(
            text = "赞 $likedNum",
            color = MaterialTheme.colorScheme.secondary,
            style = MaterialTheme.typography.titleSmall)
        Spacer(modifier = Modifier
            .width(5.dp)
            .wrapContentHeight())
        /* 点赞控件 */
        IconButton(onClick = {
            isLike = !isLike
            if (isLike){
                likedNum += 1
            } else {
                likedNum -= 1
            }
            /*TODO：处理点赞意图的回调 */

        }) {
            Image(painter =  if (isLike) painterResource(R.drawable.ic_good_true) else painterResource(R.drawable.ic_good),
                contentDescription = null)
        }
        Spacer(modifier = Modifier
            .width(5.dp)
            .wrapContentHeight())
        /* 评论数量 */
        Text(
            text = "评论 $commentNum",
            color = MaterialTheme.colorScheme.secondary,
            style = MaterialTheme.typography.titleSmall)
        Spacer(modifier = Modifier
            .width(5.dp)
            .wrapContentHeight())
        /* 评论控件 */
        IconButton(onClick = {
            isComment = !isComment
            /*TODO：处理评论区的回调 */

        }) {
            Image(painter =  if (isComment) painterResource(R.drawable.ic_comment_true) else painterResource(R.drawable.ic_comment),
                contentDescription = null)
        }
    }
}